using System;
using System.Web;

namespace ASPNETVN.PORTAL.Components.Helpers
{
    public class HttpUrlBuilder
    {
        public static string BuildUrl(int moduleID, int itemID, Enum page)
        {
            return buildUrl("~/Default.aspx", moduleID, itemID, "page=" + page);
        }

        public static string BuildUrl(int moduleID, int itemID, Enum page, string format, params object[] args)
        {
            return buildUrl("~/Default.aspx", moduleID, itemID, string.Format(format, args) + "&page=" + page);
        }
        
        //-----------------------------------------------------------------------------------------

        public static string BuildUrl(string page, int moduleID, int itemID, string format, params object[] args)
        {
            return buildUrl(page, moduleID, itemID, format, args);
        }

        public static string BuildAddUrl(int moduleID, int itemID, string format, params object[] args)
        {
            return buildUrl("~/AddPage.aspx", moduleID, itemID, format, args);
        }

        public static string BuildEditUrl(int moduleID, int itemID, string format, params object[] args)
        {
            return buildUrl("~/EditPage.aspx", moduleID, itemID, format, args);
        }

        public static string BuildAddEditUrl(int moduleID, int itemID, string format, params object[] args)
        {
            return buildUrl("~/AddEditPage.aspx", moduleID, itemID, format, args);
        }

        private static string buildUrl(string page, int moduleID, int itemID, string format, params object[] args)
        {
            string url = page;
            HttpContext context = HttpContext.Current;

            // TabIndex.
            int tabIndex = 1;
            if (context.Request.QueryString["tabindex"] != null) tabIndex = Convert.ToInt32(context.Request.QueryString["tabindex"]);

            // TabID.
            int tabID = 1;
            if (context.Request.QueryString["tabid"] != null) tabID = Convert.ToInt32(context.Request.QueryString["tabid"]);

            url += string.Format("?tabindex={0}&tabid={1}", tabIndex, tabID);

            // ModuleID.
            if (moduleID > 0) url += string.Format("&mid={0}", moduleID);

            // ItemID.
            if (itemID > 0) url += string.Format("&itemid={0}", itemID);

            if (!string.IsNullOrEmpty(format)) url += string.Format("&" + format, args);

            // ReturnUrl.
            string returnUrl = string.Empty;
            if (context.Request.QueryString["ReturnUrl"] != null) returnUrl = context.Request.QueryString["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                url += string.Format("&returnUrl={0}", context.Server.UrlEncode(context.Request.RawUrl));
            }
            return url;
        }
    }
}
